//
//  USMsgTouchIncident.m
//  us
//
//  Created by lhx on 2025/4/11.
//

#import "USMsgTouchIncident.h"

#import "EMAudioPlayerUtil.h"

#import "USChatVoiceCell.h"

@implementation USMessageEventStrategy

- (void)messageEventOperation:(USMessageViewModel *)vm {}

@end

/**
   消息事件工厂
*/
@implementation USMessageEventStrategyFactory

+ (USMessageEventStrategy * _Nonnull)getStratrgyImplWithMsgType:(EMMessageBodyType)type{
    if (type == EMMessageBodyTypeText)
        return [[TextMsgEvent alloc]init];
    if (type == EMMessageBodyTypeImage)
        return [[ImageMsgEvent alloc] init];
    if (type == EMMessageBodyTypeVoice)
        return [[VoiceMsgEvent alloc]init];
 
    return [[USMessageEventStrategy alloc]init];
}

@end

@implementation TextMsgEvent

- (void)messageEventOperation:(USMessageViewModel *)vm {
    NSLog(@"点击文字");

    EMTextMessageBody *body = (EMTextMessageBody *)vm.message.body;

}


@end



@implementation ImageMsgEvent

- (void)presentWithPath:(NSString *)tempPath{
    self.imageURL = [NSURL fileURLWithPath:tempPath];
    
    QLPreviewController *previewController = [[QLPreviewController alloc] init];
    previewController.dataSource = self;
    previewController.delegate = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.chatController presentViewController:previewController animated:YES completion:nil];
    });
}
- (void)messageEventOperation:(USMessageViewModel *)vm {
    NSLog(@"点击图片");
    
    EMImageMessageBody *body = (EMImageMessageBody *)vm.message.body;
 
    BOOL isLocal = YES;
    if (vm.message.direction == EMMessageDirectionReceive || body.localPath.length <= 0) {
        isLocal = false;
    }
 
     NSString *tempPath = [body.localPath stringByAppendingPathExtension:@"png"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:tempPath]) {
        NSLog(@"文件存在 -- %@",tempPath);
        [self presentWithPath:tempPath];
    } else {
        NSLog(@"文件不存在！");
        if (isLocal) {
            NSError *error = nil;
            [[NSFileManager defaultManager] copyItemAtPath:body.localPath toPath:tempPath error:&error];
            if (error) {
                NSLog(@"Copy error: %@", error);
            }else {
                [self presentWithPath:tempPath];
            }
            
        }else {
            
            NSURLSessionDownloadTask *downloadTask = [[NSURLSession sharedSession] downloadTaskWithURL:[NSURL URLWithString:body.remotePath] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                if (!error) {
                    // 移动下载好的文件
                    NSError *error = nil;
                    NSURL *localURL = [NSURL fileURLWithPath:tempPath];
                    
                    [[NSFileManager defaultManager] moveItemAtURL:location toURL:localURL error:&error];
                    if (error) {
                        NSLog(@"Copy error: %@", error);
                    }else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self presentWithPath:tempPath];
                        });
                    }
                    
                }
            }];
            [downloadTask resume];
        }
    }
    
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}

- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    return self.imageURL;
}
- (BOOL)previewController:(QLPreviewController *)controller shouldOpenURL:(NSURL *)url forPreviewItem:(id <QLPreviewItem>)item{
    return YES;
}
@end



@implementation VoiceMsgEvent


- (void)messageEventOperation:(USMessageViewModel *)vm {
    NSLog(@"点击音频");
    
    EMVideoMessageBody *body = (EMVideoMessageBody *)vm.message.body;
    
    
    void (^playBlock)(USMessageViewModel *aModel) = ^(USMessageViewModel *aModel) {
        if (!vm.message.isListened) {
            vm.message.isListened = YES;
        }
        
        if (!vm.message.isReadAcked) {
            [[EMClient sharedClient].chatManager sendMessageReadAck:vm.message.messageId toUser:vm.message.conversationId completion:^(EMError * _Nullable aError) {
                NSLog(@"isRead == %i",vm.message.isReadAcked);
            }];
        }
        
        [vm.cell setReadStatusHidden:YES];
        
        id model = [EMAudioPlayerUtil sharedHelper].model;
        USMessageViewModel *oldModel = (USMessageViewModel *)model;
        
        if (oldModel == vm && oldModel.isPlaying == YES) {
            //停止
            [[EMAudioPlayerUtil sharedHelper] stopPlayer];
            [EMAudioPlayerUtil sharedHelper].model = nil;
            vm.isPlaying = NO;
            [[NSNotificationCenter defaultCenter] postNotificationName:USVoicePlayerDidChangeNotification object:vm];
            
        }else{
            
            //播放
            [EMClient.sharedClient.chatManager updateMessage:vm.message completion:nil];
            vm.isPlaying = YES;
            [[NSNotificationCenter defaultCenter] postNotificationName:USVoicePlayerDidChangeNotification object:vm];
            
            [[EMAudioPlayerUtil sharedHelper] startPlayerWithPath:body.localPath model:vm completion:^(NSError * _Nonnull error) {
                
                vm.isPlaying = NO;
                [[NSNotificationCenter defaultCenter] postNotificationName:USVoicePlayerDidChangeNotification object:vm];
                
                NSLog(@"%@",error.debugDescription);

            }];
            
        }
    };
    
    if (body.downloadStatus == EMDownloadStatusSucceed) {
        playBlock(vm);
    }else if (body.downloadStatus != EMDownloadStatusSucceed || ![[NSFileManager defaultManager] fileExistsAtPath:body.localPath]) {
        
        [[EMClient sharedClient].chatManager downloadMessageAttachment:vm.message progress:^(int progress) {
            NSLog(@"voice_progress == %i",progress);
        } completion:^(EMChatMessage * _Nullable message, EMError * _Nullable error) {
            
            NSLog(@"%@",error.errorDescription);
            
            if (error) {
                
            }else {
                playBlock(vm);
            }
        }];
        return;
    }
    
}

@end
